package ai_role_api

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/res"
)

type AiRoleWorkOrderApproveRequest struct {
	ID     uint `json:"id" binding:"required"`
	Status int8 `json:"status" binding:"required,oneof=2 3"` //  2  拒绝  3 同意
}

func (air AiRoleApi) AiRoleWorkOrderApproveView(c *gin.Context) {
	var cr AiRoleWorkOrderApproveRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	var work models.AiRoleWorkOrderModel
	err = global.DB.Preload("AiRoleModel").Take(&work, cr.ID).Error
	if err != nil {
		res.FailWithMsg(c, "工单不存在")
		return
	}
	if work.Status != 1 {
		res.FailWithMsg(c, "工单已审批")
		return
	}
	switch cr.Status {
	case 2:
	case 3:
		// 同意
		switch work.Type {
		// 1 推荐  2  更新  3 删除
		case 1:
			global.DB.Model(&work.AiRoleModel).Update("is_square", true)
			air.userservice.UserScope(global.DB,
				work.UserID, global.Config.AI.RecommendRoleScope)
		case 2:
			var model models.AiRoleModel
			err = json.Unmarshal([]byte(work.AiRoleUpdateData), &model)
			if err != nil {
				res.FailWithMsg(c, "json解析角色信息失败 "+err.Error())
				return
			}
			err = global.DB.Model(&work.AiRoleModel).Updates(models.AiRoleModel{
				Title:    model.Title,
				Avatar:   model.Avatar,
				Category: model.Category,
				Abstract: model.Abstract,
				Prompt:   model.Prompt,
			}).Error
			if err != nil {
				res.FailWithMsg(c, "更新角色信息失败")
				return
			}
			air.userservice.UserScope(global.DB,
				work.UserID, global.Config.AI.UpdateRoleScope)
		case 3:
			err = global.DB.Debug().Delete(&work.AiRoleModel).Error
			fmt.Println(err)
			air.userservice.UserScope(global.DB,
				work.UserID, global.Config.AI.DeleteRoleScope)
		}

	}
	// 这里要把预加载的 AiRoleModel 置空，不然删除的角色又被创建了
	work.AiRoleModel = models.AiRoleModel{}
	global.DB.Debug().Model(&work).Update("status", cr.Status)
	res.OkWithMsg(c, "ai角色工单审批成功")
}
